<template>
  <el-dialog v-model="visible" :title="title" width="920" show-footer show-zoom resize :close-on-click-modal="false"
    :close-on-press-escape="false" @close="close">
    <template #default>
      <el-form ref="formRef" :rules="rules" :model="form" label-align="right" label-width="120" size="default"
        label-position="top">
        <el-row :gutter="20">
          <el-col :span="8" v-if="handleType != 'add'">
            <el-form-item label="盘点单" prop="location_code">
              {{ form.sea_inventory_count_order_no }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouse_id">
              <SelectWarehouse class="w-full" v-model="form.warehouse_id" :disabled="form.id" placeholder="请选择仓库">
              </SelectWarehouse>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <vxe-table :data="form.detail" :round="true" height="300">
        <vxe-column title="SKU">
          <template #default="{ row }">
            <el-input v-model="row.sku" placeholder="输入SKU" @change="changeSkU(row)" :disabled="handleType == 'view'" />
          </template>
        </vxe-column>
        <vxe-column field="custom_sku" title="自定义SKU">
          <template #default="{ row }">
            {{ row.custom_sku || '--' }}
          </template>
        </vxe-column>
        <vxe-column field="seller_sku" title="渠道SKU">
          <template #default="{ row }">
            {{ row.seller_sku || '--' }}
          </template>
        </vxe-column>
        <vxe-column field="fn_sku" title="第三方SKU">
          <template #default="{ row }">
            {{ row.fn_sku || '--' }}
          </template>
        </vxe-column>
        <vxe-column field="num" title="可用">
          <template #default="{ row }">
            {{ row.num || '--' }}
          </template>
        </vxe-column>
        <vxe-column title="盘点数量">
          <template #default="{ row }">
            <el-input v-model="row.count_num" placeholder="盘点数量" oninput="value = value.replace(/[^0-9]/g, '')"
              :disabled="handleType == 'view'" />
          </template>
        </vxe-column>
        <vxe-column title="差异数量">
          <template #default="{ row }">
            {{ Number(row.count_num - Number(row.num) || 0) }}
          </template>
        </vxe-column>
        <vxe-column field="remark" title="备注">
          <template #default="{ row }">
            <el-input v-model="row.remark" placeholder="备注" :disabled="handleType == 'view'" />
          </template>
        </vxe-column>
        <vxe-column field="opearn" title="操作" width="100" v-if="handleType != 'view'">
          <template #default="{ row, rowIndex }">
            <el-link class="mr-2" size="small" type="primary" @click="addRow">新增</el-link>
            <el-link size="small" type="primary" @click="deleteRow(rowIndex)">删除</el-link>
          </template>
        </vxe-column>
      </vxe-table>
    </template>

    <template #footer>
      <template v-if="handleType == 'view'">
        <div class="flex justify-center py-2">
          <el-button type="" @click="close">关 闭</el-button>
        </div>
      </template>
      <div class="flex justify-center py-2" v-else>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save(formRef)">保 存</el-button>
      </div>

    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { getSeaInventoryDetail, addSeaInventory, updateSeaInventory } from '../api/index'
import { getSKULocation } from '@/api/public'
import { reactive, ref, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import SelectWarehouse from '@/components/SelectWarehouse'


const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const emits = defineEmits(['query'])

const props = defineProps({
  wareDataList: {
    type: Array,
    default: [],
  },
})

const data = reactive({
  form: {},
  title: '新增',
  handleType: null,
  rules: {
    warehouse_id: [{
      required: true, message: '请选择仓库', trigger: 'blur'
    }],
  },
})
const { form, title, handleType, rules } = toRefs(data)

const statusMap = new Map([
  ['add', '新增'],
  ['edit', '编辑'],
  ['view', '查看'],
  ['out', '出库'],
])

const open = (type, id) => {
  title.value = statusMap.get(type)
  handleType.value = type
  visible.value = true
  if (id) getDetail(id)
}

const initForm = () => {
  form.value = getForm()
}
// 初始化
const getForm = () => {
  return {
    detail: [
      {
        sku: "",//sku
        custom_sku: "",//自定义sku
        num: 0,//商品编码
        count_num: '',//调拨数量
        remark: "",//备注
      }
    ]
  }
}

onMounted(() => {
  initForm()
})

const getDetail = async (id) => {
  try {
    const res = await getSeaInventoryDetail({
      id
    })
    form.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

const addRow = async () => {
  form.value.detail.push({
    sku: "",//sku
    custom_sku: "",//自定义sku
    num: 0,//商品编码
    count_num: '',//调拨数量
    remark: "",//备注
  })
}

const deleteRow = (index) => {
  if (form.value.detail.length <= 1) return
  form.value.detail.splice(index, 1)
}

const changeSkU = async (row) => {
  if (!row.sku) {
    ElMessage.error('输入sku')
    return
  }
  if (!form.value.warehouse_id) {
    ElMessage.error('请选择调出仓')
    return
  }
  try {
    const res = await getSKULocation({
      sku: row.sku,
      warehouse_id: form.value.warehouse_id,
      type: 1,
      inv_type: ['warehouse_inv']
    })
    row.sku = res.data.sku
    row.location = res.data.location
    row.custom_sku = res.data.custom_sku
    row.sku_cn_title = res.data.sku_cn_title
    row.base_sku_code = res.data.base_sku_code
    row.num = res.data.warehouse[0]?.num
    row.fn_sku = res.data.fn_sku[0]?.fn_sku
  } catch (e) {
    throw Error(e)
  }
}

const save = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      if (form.value.id) {
        updateSeaInventory(form.value)
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      } else {
        addSeaInventory(form.value)
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      }
    }
  })
}

const close = () => {
  initForm()
  visible.value = false
}
defineExpose({ open })
</script>
<style lang="scss" scoped>
.borderNone {
  :deep(.el-input__wrapper) {
    border: none;
    box-shadow: none
  }
}</style>
